"""
Created on 30-Nov-2009

@author: dexen
"""


import socket
from threading import Lock

from rpyc.utils import server

import dexen
from dexen.system.server.naming_manager import NamingManager
from dexen.system.base import service
#===============================================================================
# Globals
#===============================================================================
new_nodes = {}
dead_nodes = {}
lock = Lock()
name_mgr = None

#===============================================================================
# Service Class
#===============================================================================
class NodeRegistryService(dexen.Service):
    def on_disconnect(self):
        if hasattr(self, "name"):
            self.unregister()
    
    def on_connect(self):
        print "I am connected"
    
    def register(self, start_time):
        """
            Address is a tuple of (ip(str), port(int))
        """
        global new_nodes, name_mgr
        with lock:
            self.name = name_mgr.get_name()
            new_nodes[self.name] = start_time
            return self.name
    
    def unregister(self):
        global dead_nodes
        with lock:
            if new_nodes.has_key(self.name):
                del new_nodes[self.name]
            else:
                dead_nodes[self.name] = None
            name_mgr.release_name(self.name)
        
    def get_nodes(self):
        global new_nodes, dead_nodes
        with lock:
            ret = new_nodes, dead_nodes
            new_nodes = {}
            dead_nodes = {}
        return ret

def main():
    global name_mgr
    svr = server.ThreadedServer(NodeRegistryService,
                                protocol_config=service.default_config)
    name_mgr = NamingManager("NODE")
    svr.start()

if __name__ == "__main__":
    main()
